#! /usr/bin/env python
#coding=utf-8

from get_month_quarter import *
#from __future__ import division

db = get_db_connection()

def get_tasks_stage_avgtime_detail():
    
    #从settings.ini获取里程碑计划权重
#    settings = Ini('../apps/settings.ini')
#    milestone_weight = dict(settings.PARA.MILESTONE_WEIGHT)
#    milestone_buffer = dict(settings.PARA.MILESTONE_DELAY_DAY)
#    
#    day_buffer = milestone_buffer.get(buffer)

    req_detail = get_model('tasks_details')
    req_detail_tmp = get_model('tmp_tasks_details')
    req_dev = get_model('tasks_develop')

            
    #获取本周末日期

#    today = datetime.date.today()

    #first_day,last_day = get_week()
    req_detail_tmp.table.drop()
    req_detail_tmp.table.create()
    sql_sel = select([req_detail.c.task_id,
                      func.sum((func.datediff(req_detail.c.end_time,req_detail.c.begin_time))+1),
                      req_detail.c.stage,
                      req_detail.c.kfzx,
                      req_detail.c.tx,
                      func.min(req_detail.c.begin_time),
                      func.max(req_detail.c.end_time)],
                      and_(req_detail.c.task_id.in_(
                                              select([req_dev.c.task_id],
                                                    or_(req_dev.c.status != '4',
                                                        req_dev.c.status != '5'))))
                        ).group_by(req_detail.c.task_id,req_detail.c.stage)

    
    rs_sql_sel =  sql_sel.execute()
    data = {}
    
    for row in rs_sql_sel:
        task_id,num,stage,kfzx,tx,begin_time,end_time =row
        data['task_id'] = task_id
        data['begin_time'] = begin_time
        data['end_time'] = end_time
        data['num'] = num
        data['stage'] = stage
        data['kfzx'] = kfzx
        data['tx'] = tx
        r = req_detail_tmp(**data)
        r.save()
    
#    sql_avg = select([func.avg(req_detail_tmp.c.num),
#                        req_detail_tmp.c.kfzx,
#                        req_detail_tmp.c.stage]
#                     ).group_by(req_detail_tmp.c.kfzx,req_detail_tmp.c.stage)
#    return data


if __name__ == '__main__':
    try:
        db.begin()
        get_tasks_stage_avgtime_detail()
        db.commit()
        log.info("finish")
    except Exception, e:
        db.rollback()
        log.exception(e)
        log.error('error')
        raise
